import express from 'express';
import fs from 'fs';
import path from 'path';
import { matchRoutes } from 'react-router-config';
import httpProxy from 'express-http-proxy';
import favicon from 'serve-favicon';
import serverRender from './utils';
import routes from '../client/Routers';
import { getStores } from '../client/store/store';

const EJS_PATH = path.resolve(process.cwd(), './serverRender', 'index.ejs');
const PROXY_SERVER = 'blogapi.w-ming99.cn';
// const PROXY_SERVER = 'localhost:9004';

function getEjsTemplate() {
    return new Promise((resolve, reject) => {
        fs.readFile(EJS_PATH, { encoding: 'utf-8' }, (err, data) => {
            if (err) reject(err);
            resolve(data);
        });
    });
}

const app = express();

app.use(favicon(path.resolve(process.cwd(), './public', 'favicon.ico')));
app.use(express.static('dist'));

app.use('/api', httpProxy(PROXY_SERVER, {
    proxyReqPathResolver(req) {
        return `/api${req.url}`;
    },
}));

app.get('*', (req, res) => {
    getEjsTemplate().then((template) => {
        const store = getStores(true);
        const promises = [];
        const matchedRoutes = matchRoutes(routes, req.path);
        matchedRoutes.forEach((item) => {
            if (item.route.loadData) {
                promises.push(item.route.loadData(store, item.match));
            }
        });
        Promise.all(promises).then(() => {
            const context = {};
            const html = serverRender(store, routes, req, context, template);

            if (context.action === 'REPLACE') {
                res.redirect(301, '/');
            } else {
                res.send(html);
            }
        });
    });
});

app.listen(9006, () => {
    console.log('Server is running: http://localhost:9006');
});
